<?php


namespace app\api\controller\v1;
use addons\epay\library\Service;
use app\api\model\v1\VipOrder;
use app\common\controller\Api;
use think\Db;


class Notify  extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function vip_order_notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }
        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
//        $dir = './log/order_refund_e/'; //设置目录
//        if (!file_exists($dir)) {
//            mkdir($dir, 0755, true);
//        }
//        file_put_contents($dir . date('Ymd', time()) . "_1.txt", var_export($data, true) . PHP_EOL, FILE_APPEND);
        Db::startTrans();
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            //写逻辑
            $order = VipOrder::where('order_no', $out_trade_no)->find();
            if (!$order || $order->paid_at || $order->status) {
                return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
            }
            $order->paid_at = time();
            $order->payment_no = $data['transaction_id'];
            $order->payment_method = $paytype;
            $order->status = 1;
            $order->save();
            $userModel = \app\api\model\v1\User::find($order->user_id);
            $userModel->is_vip = 1;
            //1个月固定为30天，12月固定为365天
            if ($order->month == 12) {
                $days = 365;
            } else {
                $days = $order->month * 30;
            }
            if ($userModel->vip_expire_at > time()) { //vip未过期
                $date = date('Y-m-d H:i:s', $userModel->vip_expire_at);
                $addVipDate = date('Y-m-d H:i:s', strtotime("{$date} + {$days} day"));
            } else {
                $date = date('Y-m-d H:i:s');
                $addVipDate = date('Y-m-d H:i:s', strtotime("{$date} + {$days} day"));
            }
            $userModel->vip_expire_at = strtotime($addVipDate);
            $userModel->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
}